using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public interface ButtonNotice
    {
        void Click();
    }

    public class ButtonHelper : NodeHelper
    {
        public AudioClip clip;
        public SoundType soundType;
        public UIEvent uiEvent;
        public NodeHelper[] list;
        public bool isSwitch;
        public bool invert;
        public bool disabled;
        private Button _Button;
        private ButtonNotice _notice;

        protected Button Button
        {
            get
            {
                if (_Button == null) _Button = UnityTools.GetComponentRequire<Button>(gameObject);
                return _Button;
            }
        }

        protected override BindDataType bindDataType => BindDataType.Bool;

        protected override void Start()
        {
            if (Button != null) Button.onClick.AddListener(BindClick);
        }

        public void Set(ButtonNotice notice)
        {
            _notice = notice;
        }

        protected override void BindData(bool b)
        {
            b = invert ? !b : b;
            for (var i = 0; i < list.Length; i++) list[i].SetData(b);

            if (isSwitch) return;
            Button.interactable = b;
        }

        private void BindClick()
        {
            if (soundType != SoundType.None)
                Game.single.PlayEFF(soundType);
            else if (clip != null) Game.single.PlayEFF(clip);

            if (_notice != null) _notice.Click();
            
            if (disabled) return;
            
            if (uiEvent != UIEvent.None)
                Emit(uiEvent);
            else
                Click();
        }

        public void SetButton(Button button)
        {
            button.onClick.AddListener(BindClick);
        }
    }
}